import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userApi } from '../services'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const accessToken = ref(localStorage.getItem('accessToken') || null)
  const refreshToken = ref(localStorage.getItem('refreshToken') || null)
  const user = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))
  const loading = ref(false)
  const error = ref(null)

  // 登录
  const login = async (username, password) => {
    try {
      loading.value = true
      error.value = null
      
      const result = await userApi.login(username, password)
      
      if (result.success) {
        // 更新状态
        accessToken.value = result.data.access
        refreshToken.value = result.data.refresh
        user.value = result.data
        
        // 保存到localStorage
        localStorage.setItem('accessToken', result.data.access)
        localStorage.setItem('refreshToken', result.data.refresh)
        localStorage.setItem('userInfo', JSON.stringify(result.data))
        
        ElMessage.success('登录成功')
        return true
      } else {
        // 处理错误
        error.value = result.error
        ElMessage.error(result.error)
        if (result.details) {
          console.error('Login error details:', result.details)
        }
        return false
      }
    } catch (err) {
      error.value = err.message || '登录失败'
      ElMessage.error(error.value)
      console.error('Login error:', err)
      return false
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      loading.value = true
      await userApi.logout()
      
      // 清除状态
      accessToken.value = null
      refreshToken.value = null
      user.value = null
      
      // 清除localStorage
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
      
      ElMessage.success('退出登录成功')
      return true
    } catch (err) {
      error.value = err.message || '登出失败'
      ElMessage.error(error.value)
      return false
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      if (!accessToken.value) return null
      
      loading.value = true
      const response = await userApi.getUserInfo()
      
      // 更新用户信息
      user.value = response.data
      localStorage.setItem('userInfo', JSON.stringify(response.data))
      
      return response.data
    } catch (err) {
      error.value = err.message || '获取用户信息失败'
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  // 检查是否已登录
  const isLoggedIn = () => userApi.isLoggedIn()

  return {
    accessToken,
    refreshToken,
    user,
    loading,
    error,
    login,
    logout,
    getUserInfo,
    isLoggedIn
  }
}) 